package pri.jz.keeper.ui.content.personal.userinfo

import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import pri.jz.keeper.entity.User
import pri.jz.keeper.repository.UserRepository
import pri.jz.keeper.ui.base.BaseViewModel

/**
 *Author by: JZ
 *Email: 2451756617@qq.com
 *PS:
 */
class UserInfoViewModel(application: Application) : BaseViewModel(application) {
    private val userRepository = UserRepository.getIns()
    private val _user = userRepository.user
    val user: LiveData<User?>
        get() = _user
    //事件分发
    private val _intent = MutableStateFlow<UserInfoIntent>(UserInfoIntent.OnDefault)

    var nameText by mutableStateOf(user.value?.name ?: "用户")
        private set
    var sexText by mutableStateOf(user.value?.sex ?: "外星人")
        private set

    init {
        viewModelScope.launch {
            _intent.collect { intent ->
                when (intent) {
                    is UserInfoIntent.OnDefault -> {}
                    is UserInfoIntent.OnNameValueChange -> onNameValueChange(intent.text)
                    is UserInfoIntent.OnSexValueChange -> onSexValueChange(intent.sex)
                    is UserInfoIntent.OnHeadIconClick -> onHeadIconClick()
                    is UserInfoIntent.OnSaveUserInfo -> onSaveUserInfo()
                }
            }
        }
    }

    /**
     * 事件分发
     * @param intent 要进行的事件
     */
    fun dispatcher(intent: UserInfoIntent) {
        _intent.value = intent
    }

    private fun onNameValueChange(name: String) {
        nameText = name
    }

    private fun onSexValueChange(sex: String) {
        sexText = sex
    }

    private fun onHeadIconClick() {

    }

    /**
     * 保存用户修改数据
     */
    private fun onSaveUserInfo() {
        viewModelScope.launch {
            userRepository.saveUser()
        }
    }

}